﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Microsoft.CSharp;

namespace CodeLibrary.Reflection.CodeDOM
{
    internal class Class1
    {
        private void test()
        {
            string code = null;

            // 1. 生成要编译的代码。（示例为了简单直接从程序集内的资源中读取）
            Stream stram = typeof(Class1).Assembly
                                           .GetManifestResourceStream("TestOptimizeReflection.用户手册.txt");
            using (StreamReader sr = new StreamReader(stram))
            {
                code = sr.ReadToEnd();
            }
            // 2. 设置编译参数，主要是指定将要引用哪些程序集
            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("OptimizeReflection.dll");

            // 3. 获取编译器并编译代码
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict["CompilerVersion"] = "v3.5";
            dict["WarnAsError"] = "false";
            CSharpCodeProvider csProvider = new CSharpCodeProvider(dict);
            CompilerResults cr = csProvider.CompileAssemblyFromSource(cp, code);

            // 4. 检查有没有编译错误
            if (cr.Errors != null && cr.Errors.HasErrors)
            {
                foreach (CompilerError error in cr.Errors)
                    Console.WriteLine(error.ErrorText);
                return;
            }

            // 5. 获取编译结果，它是编译后的程序集
            Assembly asm = cr.CompiledAssembly;
            Type t = asm.GetType("OptimizeReflection.用户手册");
            MethodInfo method = t.GetMethod("Main");
            method.Invoke(null, null);

        }
    }
}
